package tc.alert.tckejisoc.rule;

import com.jayway.jsonpath.JsonPath;

import java.util.regex.Pattern;
/**
 * author: cyq
 * time: 2024/10/23 17:37
 */
public class RuleMatcher {
    private final String type;
    private final Pattern regexPattern;
    private final JsonPath jsonPath;

    public RuleMatcher(String type, String pattern) {
        this.type = type;
        switch (type) {
            case "regex":
                this.regexPattern = Pattern.compile(pattern);
                this.jsonPath = null;
                break;
            case "jsonpath":
                this.jsonPath = JsonPath.compile(pattern);
                this.regexPattern = null;
                break;
            default:
                throw new IllegalArgumentException("Unsupported matcher type: " + type);
        }
    }

    public boolean matches(String log) {
        if ("regex".equals(type)) {
            return regexPattern.matcher(log).find();
        } else if ("jsonpath".equals(type)) {
            try {
                return jsonPath.read(log) != null;
            } catch (Exception e) {
                return false;
            }
        }
        return false;
    }
}